import axios from 'axios'
import { VueAxios } from './axios.js'
import  userInfoStore from '../store/user.js'
import { Authorization } from '../store/mutation-types.js'


// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  timeout: 60000 // 请求超时时间
})


// 异常拦截处理器
const errorHandler = (error) => {
  const user = userInfoStore()
  if (error.response) {
    const data = error.response.data
    if (error.response.status === 403) {
      // $uiMsg.error(data.message)
    }
    if (error.response.status === 401 && !(data.result && data.result.isLogin)) {
      // $uiMsg.error('授权失败')
      // 从 localstorage 获取 token
      const token = user.token
      if (token) {
        //删除用户过期令牌
        user.LoginOut()
      }
    }
    if (error.response.status === 500) {
      // $uiMsg.error("500 服务器开小差了~")
    }
    return Promise.reject(error)
  }
}

  // request interceptor
  request.interceptors.request.use(config => {
    const user = userInfoStore()

    const token = user.token
    // 如果 token 存在
    // 让每个请求携带自定义 token 请根据实际情况自行修改
    if (token && config.headers[Authorization] == null) {
      config.headers[Authorization] = token
    }
    return config
  }, errorHandler)

  // response interceptor
  request.interceptors.response.use((response) => {
    return response.data
  }, errorHandler)

  const installer = {
    vm: {},
    install(Vue) {
      Vue.use(VueAxios, request)
    }
  }

  export default request

  export {
    installer as VueAxios,
    request as axios
  }
